package com.hemaapp.yjnh.view;

import android.app.Dialog;
import android.content.Context;
import android.os.AsyncTask;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.hemaapp.hm_FrameWork.result.HemaPageArrayResult;
import com.hemaapp.yjnh.BaseNetTaskExecuteListener;
import com.hemaapp.yjnh.BaseNetWorker;
import com.hemaapp.yjnh.BaseUtil;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.bean.ProvinceCityDistrict;
import com.hemaapp.yjnh.db.CityDBClient;
import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.HemaNetWorker;
import com.hemaapp.hm_FrameWork.result.HemaArrayResult;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.yjnh.view.singlewheel.OnItemSelectedListener;
import com.hemaapp.yjnh.view.singlewheel.ProvinceLoopView;

import java.util.ArrayList;
import java.util.List;

/**
 * 类描述：省市县三级联动dialog
 * 创建人：GuiyouZhang
 * 创建时间：2016/6/23 13:14
 * 修改备注：
 */
public class ProvinceCityDialog {

    ArrayList<String> provinceDatas = new ArrayList<>();
    ArrayList<String> cityDatas = new ArrayList<>();
    ArrayList<String> districtDatas = new ArrayList<>();
    List<ProvinceCityDistrict> provinceList = null;
    List<ProvinceCityDistrict> cityList = null;
    List<ProvinceCityDistrict> districtList = null;
    CityDBClient cityDBClient;
    private Context context;
    private Dialog dialog;
    private Display display;
    private onSelectedItemListener listener = null;
    private TextView tvCancel;
    private TextView tvOK;
    private ProvinceLoopView provinceView;
    private ProvinceLoopView cityView;
    private ProvinceLoopView countyView;
    private BaseNetWorker netWorker;

    public ProvinceCityDialog(Context context) {
        this.context = context;
        WindowManager windowManager = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        display = windowManager.getDefaultDisplay();
        cityDBClient = new CityDBClient(context);
        this.netWorker = new BaseNetWorker(context);
        this.netWorker.setOnTaskExecuteListener(new TaskExecuteListener(
                context));
    }

    public void getDistrckList () {
        this.netWorker.getDistrictList("-2");
    }

    public ArrayList<String> getProvinceDatas() {
        return provinceDatas;
    }

    public void setProvinceDatas(ArrayList<String> provinceDatas) {
        this.provinceDatas = provinceDatas;
        provinceView.setItems(provinceDatas);
    }

    public ArrayList<String> getCityDatas() {
        return cityDatas;
    }

    public void setCityDatas(ArrayList<String> cityDatas) {
        this.cityDatas = cityDatas;
        cityView.setItems(cityDatas);
    }

    public ArrayList<String> getCountyDatas() {
        return districtDatas;
    }

    public void setCountyDatas(ArrayList<String> countyDatas) {
        this.districtDatas = countyDatas;
        countyView.setItems(countyDatas);
    }

    public ProvinceCityDialog builder() {
        View view = LayoutInflater.from(context).inflate(R.layout.dialog_province_city, null);
        view.setMinimumWidth(display.getWidth());
        dialog = new Dialog(context, R.style.ActionSheetDialogStyle);
        dialog.setContentView(view);
        tvCancel = (TextView) view.findViewById(R.id.tv_cancel);
        tvOK = (TextView) view.findViewById(R.id.tv_ok);
        provinceView = (ProvinceLoopView) view.findViewById(R.id.province_loop);
        cityView = (ProvinceLoopView) view.findViewById(R.id.city_loop);
        countyView = (ProvinceLoopView) view.findViewById(R.id.county_loop);
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        tvOK.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(listener != null){
                    listener.onSelected(provinceView.getSelectedItem(), cityView.getSelectedItem()
                                            , countyView.getSelectedItem());
                }
                dismiss();
            }
        });
        //设置滑动监听
        provinceView.setListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(int index) {
                if (index>=0 && index < provinceList.size())
                    getDataFromDB(provinceList.get(index).getId(), "1");
            }
        });
        cityView.setListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(int index) {
                if (index>=0 && index < cityList.size())
                    getDataFromDB(cityList.get(index).getId(), "2");
            }
        });
        countyView.setListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(int index) {

            }
        });
        //设置是否循环播放
        provinceView.setNotLoop();
        cityView.setNotLoop();
        countyView.setNotLoop();

        int one = BaseUtil.dip2px(context, 1);
        provinceView.setViewPadding(one*2, 0, one*2, 0);
        cityView.setViewPadding(one*2, 0, one*2, 0);
        countyView.setViewPadding(one*2, 0, one*2, 0);
        //设置原始数据
//        provinceView.setItems(provinceDatas);
//        cityView.setItems(cityDatas);
//        countyView.setItems(countyDatas);
        //设置初始位置
//        provinceView.setInitPosition(0);
//        cityView.setInitPosition(0);
//        countyView.setInitPosition(0);
        //设置字体大小
//        provinceView.setTextSize(10);
//        cityView.setTextSize(10);
//        countyView.setTextSize(10);

        Window dialogWindow = dialog.getWindow();
        dialogWindow.setGravity(Gravity.LEFT | Gravity.BOTTOM);
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.x = 0;
        lp.y = 0;
        dialogWindow.setAttributes(lp);
        return this;
    }

    public void show() {
        initProvinceDatas(context);
        dialog.show();
    }

    public void dismiss() {
        dialog.dismiss();
    }

    public void setListener(onSelectedItemListener listener) {
        this.listener = listener;
    }

    protected void initProvinceDatas(Context context) {
        if (cityDBClient.getDataCount() == 0) {//如果数据库中的数据为空，那么去网络获取
            getDistrckList();
        }else {
            //从数据库取数据
//            new getDistrictTask().execute("0", "0");
            getDataFromDB("0", "0");
        }
    }
    public int getCityDataCount() {
        return cityDBClient.getDataCount();
    }

    private void getDataFromDB(String parentId, String type) {
        if (type.equals("0")) {
            provinceList = cityDBClient.getCities(parentId);
            provinceDatas.clear();
            if (provinceList.size() > 0) {
                for (ProvinceCityDistrict district : provinceList) {
                    provinceDatas.add(district.getName());
                }
                provinceView.setItems(provinceDatas);
                provinceView.setInitPosition(0);
                getDataFromDB(provinceList.get(0).getId(), "1");
            }else {
                provinceDatas.add("暂无");
                provinceView.setItems(provinceDatas);
                provinceView.setInitPosition(0);
            }
        }else if (type.equals("1")) {
            cityList = cityDBClient.getCities(parentId);
            cityDatas.clear();
            if (cityList.size() > 0) {
                for (ProvinceCityDistrict district:cityList) {
                    cityDatas.add(district.getName());
                }
                cityView.setInitPosition(0);
                cityView.setItems(cityDatas);
                getDataFromDB(cityList.get(0).getId(), "2");
            }else {
                cityDatas.add("暂无");
                cityView.setItems(cityDatas);
                cityView.setInitPosition(0);
            }
        }else if (type.equals("2")) {
            districtList = cityDBClient.getCities(parentId);
            districtDatas.clear();
            if (districtList.size() > 0) {
                for (ProvinceCityDistrict district:districtList) {
                    districtDatas.add(district.getName());
                }
                countyView.setItems(districtDatas);
                countyView.setInitPosition(0);
            }else {
                districtDatas.add("暂无");
                countyView.setItems(districtDatas);
                countyView.setInitPosition(0);
            }
        }
    }

    public interface onSelectedItemListener {
        void onSelected(int province, int city, int county);
    }

    private class TaskExecuteListener extends BaseNetTaskExecuteListener {

        /**
         * @param context
         */
        public TaskExecuteListener(Context context) {
            super(context);
        }

        @Override
        public void onPreExecute(HemaNetWorker netWorker, HemaNetTask netTask) {

        }

        @Override
        public void onPostExecute(HemaNetWorker netWorker, HemaNetTask netTask) {

        }

        @Override
        public void onServerSuccess(HemaNetWorker netWorker,
                                    HemaNetTask netTask, HemaBaseResult baseResult) {
            HemaPageArrayResult<ProvinceCityDistrict> result = (HemaPageArrayResult<ProvinceCityDistrict>) baseResult;
            ArrayList<ProvinceCityDistrict> districts = result.getObjects();
            if (districts != null && districts.size() > 0) {
                new SaveDistrictTask().execute(districts);
            }
        }

        @Override
        public void onServerFailed(HemaNetWorker netWorker,
                                   HemaNetTask netTask, HemaBaseResult baseResult) {

        }

        @Override
        public void onExecuteFailed(HemaNetWorker netWorker,
                                    HemaNetTask netTask, int failedType) {

        }

    }

    private class SaveDistrictTask extends AsyncTask<ArrayList<ProvinceCityDistrict>, Void, Void> {

        @Override
        protected void onPreExecute() {
            // XtomProcessDialog.show(mContext, R.string.loading);
        }

        @Override
        protected Void doInBackground(ArrayList<ProvinceCityDistrict>... params) {
            cityDBClient.clear();
            for (ProvinceCityDistrict district : params[0]) {
                cityDBClient.insert(district);
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void v) {
            if (dialog != null) {
                initProvinceDatas(context);
            }
        }
    }
}
